package com.hc.sp02.item.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import sp01.pojo.Item;
import sp01.service.ItemService;
import sp01.util.JsonResult;

import java.util.List;
import java.util.Random;

/**
 * @author He
 * @date 2021/8/30 14:46
 */
@RestController
@Slf4j
public class ItemController {
    @Autowired
    private ItemService itemService;

    @Value("${server.port}")
    private int port;

    //获取订单中的商品数据
    @GetMapping("/{orderId}")
    public JsonResult<List<Item>> getItems(@PathVariable String orderId) throws InterruptedException {
        log.info("获取订单的商品列表,orderId=" + orderId);
        //90%概率随机延迟
        if (Math.random() < 0.9) {
            //随机延迟0-5秒
            int t = new Random().nextInt(5000);
            log.info("延迟:"+t);
            Thread.sleep(t);
        }
        List<Item> items = itemService.getItems(orderId);
        JsonResult j = JsonResult.ok().msg("port:"+port).data(items);
        return j;
    }

    //减少商品库存
    @PostMapping("/decreaseNumbers")
    public JsonResult<?> decreaseNumbers(@RequestBody List<Item> items) {
        itemService.decreaseNumbers(items);
        return JsonResult.ok().msg("减少商品库存成功");
    }

}
